package com.mengxuegu.springboot.feng;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
@Controller
public class FileController {

    @Value("${FilePath}")
    private String FilePath;

    public String getFilePath() {
        return FilePath;
    }

    //去上传页面
    @GetMapping("/upload")
    public  String upload (){


         Integer a = 1/0 ;

        return "fileupload/upload";
    }

    //上传文件
    @ResponseBody
    @RequestMapping(value = "/uploadup",method = RequestMethod.POST)
    public String uploada(@RequestParam("file") MultipartFile file ){
        //获取原始名字
        String originalFilename = file.getOriginalFilename();
        //获取后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //文件保存路径
        String  filePath = FilePath;
        //文件名重命名, 防止重复
        String s = filePath + UUID.randomUUID() + originalFilename;
        //文件对象
        File file1 = new File(s);
        //判断路径是否存在, 不存在就创建
        if(!file1.getParentFile().exists()){
            file1.getParentFile().mkdirs();
        }
        //保存文件
        try {
            file.transferTo(file1);
            return  "成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "失败";
    }

    //下载文件
    @RequestMapping("/download")
    public void download(HttpServletResponse response) throws Exception {
        // 文件地址，真实环境是存放在数据库中的
        File file = new File("D:\\upload\\a.txt");
        // 穿件输入对象
        FileInputStream fis = new FileInputStream(file);
        // 设置相关格式
        response.setContentType("application/force-download");
        // 设置下载后的文件名以及header
        response.addHeader("Content-disposition", "attachment;fileName=" + "a.txt");
        // 创建输出对象
        OutputStream os = response.getOutputStream();
        // 常规操作
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        fis.close();
    }
}
